package com.atguigu.yygh.user.controller;

import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.AuthContextHolder;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 杨林
 * @create 2022-11-10 14:06 星期四
 * description:
 */
@RestController
@RequestMapping("/api/user")
public class UserInfoApiController {

    @Autowired
    private UserInfoService userInfoService;

    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo){
        //返回name + token
        //对loginVo 进行非空判断
        if (loginVo == null){
            throw new YyghException(20001,"登录数据异常");
        }
        Map<String, Object> map = userInfoService.login(loginVo);
        return R.ok().data("info",map);
    }

    //用户认证
    @PostMapping("auth/userAuth")
    public R userAuth(@RequestBody UserAuthVo userAuthVo, HttpServletRequest request){
        long userId = AuthContextHolder.getUserId(request);
        userInfoService.userAuth(userId, userAuthVo);
        return R.ok();
    }

    //获取当前用户信息
    @GetMapping("auth/getUserInfo")
    public R getUserInfo(HttpServletRequest request){
        //获取userId
        long userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)){
            throw new YyghException(20001, "用户id不能为空");
        }
        UserInfo userInfo = userInfoService.getById(userId);
        //设置认证状态  0：未认证  1：认证中  2：认证完成  -1：认证失败
        Integer authStatus = userInfo.getAuthStatus();  //用户的认证状态
        String authStatusString = "";
//        AuthStatusEnum[] values = AuthStatusEnum.values();
//        for (int i = 0; i < values.length; i++) {
//            AuthStatusEnum statusEnum = values[i];
//            if (statusEnum.getStatus().intValue() == authStatus){
//                authStatusString = statusEnum.getName();
//            }
//        }
        authStatusString = AuthStatusEnum.getStatusNameByStatus(authStatus);
        userInfo.getParam().put("authStatusString", authStatusString);
        return R.ok().data("userInfo",userInfo);
    }
}
